local skynet = require "skynet"
local s = require "service"
local CMD = require "game_cmd"

s.client = {}
s.gate = nil

require "scene"

s.resp.client = function(source, cmd, msg)
    s.gate = source
    if s.client[cmd] then
        local ret_msg, cmd_id = s.client[cmd](msg, source)
        if ret_msg then
            skynet.send(source, "lua", "send", s.id, ret_msg, cmd_id)
        end
    else
        local msg_ret = {
            cmd = CMD.SERVER_COMMON_RET,
            status = -1,
            msg = cmd .. "：找不到这个指令"
        }
        skynet.error("s.resp.client fail", cmd)
        skynet.send(source, "lua", "send", s.id, msg_ret, CMD.SERVER_COMMON_RET)
    end
end

-- 客户端消息
s.client.work = function(msg)
    s.data.coin = s.data.coin + 1
    return {"work", s.data.coin}
end

s.client.exit = function(msg)
    skynet.error("玩家关闭游戏", s.id, s.name)
    skynet.send(s.gate, "lua", "kick", s.id)
end

s.client.logout = function(msg)
    skynet.error("玩家退出游戏", s.id, s.name)
    skynet.send(s.gate, "lua", "logout", s.id)
end


-- 服务间消息
s.resp.kick = function(source)
    skynet.error("agent kick")
    s.leave_scene()
    skynet.error("agent kick11")
    -- 在此处保存角色数据
    skynet.call("mysql_node", "lua", "update_exp", s.id, s.data)
    skynet.error("agent kick22")
end

s.resp.exit = function(source)
    -- s.leave_scene()
    -- -- 在此处保存角色数据
    -- skynet.call("mysql_node", "lua", "update_exp", s.id, s.data)
    skynet.exit()
end

s.resp.send = function(source, msg, cmd_id)
    skynet.send(s.gate, "lua", "send", s.id, msg, cmd_id)
end

-- 每天第一次登陆调用
function first_login_day()
    skynet.error("first_login_day")
end

s.init = function()
    -- 在此处加载角色数据
    local bSuccess, data = skynet.call("mysql_node", "lua", "query_player_by_id", s.id)
    if bSuccess then
        s.data = {
            exp = data.exp,
            coin = 100,
            hp = 200
        }
    else
        skynet.error("加载角色数据失败,id:", s.id)
    end

end

s.start(...)
